package com.cjf.androidstudy.utils;

import android.content.Context;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileUtils {

    /**
     * 将内容保存到文件里面
     *
     * @param editTextContent
     */
    public static void saveData(Context context, String fileName, String editTextContent) throws IOException {
        FileOutputStream fileOutputStream = null;
        BufferedWriter bufferedWriter = null;
        try {
            fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            bufferedWriter.write(editTextContent);
        } catch (Exception e) {
            throw e;
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    throw e;
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw e;
                }
            }
        }
    }

    /**
     * 从文件中读取数据
     *
     * @param context
     * @param fileName
     * @return
     * @throws IOException
     */
    public static String loadData(Context context, String fileName) throws IOException {
        FileInputStream in = null;
        BufferedReader bufferedReader = null;
        StringBuilder content = new StringBuilder();
        try {
            File file = context.getFileStreamPath(fileName);
            if (!file.exists()) {
                return "";
            }
            in = context.openFileInput(fileName);
            bufferedReader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line);
            }
        } catch (Exception e) {
            throw e;
        }
        return content.toString();
    }
}
